package com.foxchen.ddns.service.impl.v6;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foxchen.ddns.service.IpGetServiceV6;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("http://10.0.0.1")
public class RouterGetServiceImpl implements IpGetServiceV6 {
    private static final String LOGIN_URL= "/cgi-bin/luci";
    private static final String IPV6GET_URL= "/ubus";
    private static final String PARAM = "[{\"jsonrpc\":\"2.0\",\"id\":-1,\"method\":\"call\",\"params\":[\"%s\",\"luci-rpc\",\"getNetworkDevices\",{}]}]";

    @Override
    @SneakyThrows
    @SuppressWarnings("unchecked")
    public String getIp(String routerUrl) {
        // 登录鉴权
        Map<String, Object> formParams = new HashMap<>();
        formParams.put("luci_username", "root");
        formParams.put("luci_password", "Chenjin1314...");
        try(HttpResponse execute = HttpUtil.createPost(routerUrl + LOGIN_URL).form(formParams).execute()){
            // 获取鉴权的cookie
            String sysauthHttp = execute.getCookie("sysauth_http").getValue();
            // 请求参数
            String realParam = String.format(PARAM, sysauthHttp);

            try(HttpResponse execute1 = HttpUtil.createPost(routerUrl + IPV6GET_URL).body(realParam).execute()){
                // 解析ipv6
                String body = execute1.body();
                List<Map<String,Object>> result = (List<Map<String,Object>>) new ObjectMapper().readValue(body, new TypeReference<Object>() {});

                if(CollectionUtils.isEmpty(result)){
                    return StringUtils.EMPTY;
                }

                // 从json解析数据
                Map<String, Object> mapData = result.get(0);
                List<Object> resultList = (List<Object>) mapData.get("result");
                Map<String,Object> resultMap = (Map<String,Object>)resultList.get(1);
                return (String)((Map<String, Object>) ((List<Object>) ((Map<String, Object>) resultMap.get("pppoe-wan")).get("ip6addrs")).get(0)).get("address");
            }
        }
    }
}
